package com.imax.center.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.imax.center.constant.EzvizApiConstants;
import com.imax.center.constant.RedisConstants;
import com.imax.center.service.EzvizTokenService;
import com.imax.center.cache.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class EzvizTokenServiceImpl implements EzvizTokenService {

    @Value("${ezviz.app-key}")
    private String appKey;

    @Value("${ezviz.app-secret}")
    private String appSecret;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisService redisService;

    @Override
    public String getAccessToken() {
        // 从Redis缓存中获取token
        String accessToken = (String) redisService.get(RedisConstants.EZVIZ_TOKEN_KEY);
        
        // 如果缓存中没有token，则从萤石云获取
        if (accessToken == null) {
            synchronized (this) {
                // 双重检查，防止并发问题
                accessToken = (String) redisService.get(RedisConstants.EZVIZ_TOKEN_KEY);
                if (accessToken == null) {
                    accessToken = this.refreshAccessToken();
                }
            }
        }
        
        return accessToken;
    }

    private String refreshAccessToken() {
        try {
            String url = String.format("%s?appKey=%s&appSecret=%s",
                    EzvizApiConstants.TOKEN_GET_URL, appKey, appSecret);

            String response = restTemplate.postForObject(url, null, String.class);
            JSONObject jsonResponse = JSONObject.parseObject(response);

            log.info("萤石云获取token响应: {}", jsonResponse);

            if (jsonResponse != null && "200".equals(jsonResponse.getString("code"))) {
                JSONObject data = jsonResponse.getJSONObject("data");
                String accessToken = data.getString("accessToken");
                long expireTime = data.getLongValue("expireTime");

                // 将token存入Redis缓存，设置过期时间为6天
                redisService.set(RedisConstants.EZVIZ_TOKEN_KEY, accessToken, 
                        RedisConstants.EZVIZ_TOKEN_EXPIRE, TimeUnit.DAYS);
                
                log.info("成功更新萤石云token，将在{}秒后过期", RedisConstants.EZVIZ_TOKEN_EXPIRE);
                
                return accessToken;
            } else {
                String errorMsg = jsonResponse != null ? jsonResponse.getString("msg") : "获取访问令牌失败";
                log.error("获取萤石云token失败: {}", errorMsg);
                throw new RuntimeException(errorMsg);
            }
        } catch (Exception e) {
            log.error("刷新萤石云token异常: ", e);
            throw new RuntimeException("刷新token失败", e);
        }
    }
} 